package com.xros.demo.fileserver.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: mzp
 * @Description: 文件工具类
 * @Date: 2024/3/28 15:17
 * @Version: 1.0
 */
public class FileUtils {


    /**
     * 获取文件的输入流
     *
     * @param inputStream
     * @return
     */
    public static String getFileMd5(InputStream inputStream) {

        try {
            return DigestUtils.md5Hex(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean saveMultipartFileToLocal(byte[] fileBytes, String path) {
        return saveMultipartFileToLocal(fileBytes, path, true);

    }

    public static boolean saveMultipartFileToLocal(byte[] fileBytes, String path, boolean isFile) {
        try {
            //如果保存的是文件
            if (isFile) {

                //如果文件不存在
                if (!Files.exists(Paths.get(path))) {

                    final Path parent = Paths.get(path).getParent();
                    //父级目录也不存在
                    if (!Files.exists(parent)) {
                        Files.createDirectories(parent);
                    }
                }

                Files.write(Paths.get(path), fileBytes);
            } else {
                Files.createDirectories(Paths.get(path));
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;

    }
}
